<template>
  <el-dialog :title="form.id ? $t('common.editBtn') : $t('common.addBtn')" v-model="visible" :close-on-click-modal="false"
    draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.name')" prop="name">
            <el-input v-model="form.name" :placeholder="$t('Shop.inputNameTip')" clearable show-word-limit
              :maxlength="128" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.state')" prop="state">
            <el-select v-model="form.state" :placeholder="$t('Shop.inputStateTip')" clearable filterable>
              <el-option :value="item.value" :label="item.label" v-for="(item, index) in common_state_enable"
                :key="index"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.contacts')" prop="contacts">
            <el-input v-model="form.contacts" :placeholder="$t('Shop.inputContactsTip')" clearable show-word-limit
              :maxlength="50" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.contactPhone')" prop="contactPhone">
            <el-input v-model="form.contactPhone" :placeholder="$t('Shop.inputContactPhoneTip')" clearable show-word-limit
              :maxlength="20" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.otherPhone')" prop="otherPhone">
            <el-input v-model="form.otherPhone" :placeholder="$t('Shop.inputOtherPhoneTip')" clearable show-word-limit
              :maxlength="100" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.boss')" prop="boss">
            <el-input v-model="form.boss" :placeholder="$t('Shop.inputBossTip')" clearable show-word-limit
              :maxlength="50" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.bossPhone')" prop="bossPhone">
            <el-input v-model="form.bossPhone" :placeholder="$t('Shop.inputBossPhoneTip')" clearable show-word-limit
              :maxlength="20" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.legalPerson')" prop="legalPerson">
            <el-input v-model="form.legalPerson" :placeholder="$t('Shop.inputLegalPersonTip')" clearable show-word-limit
              :maxlength="50" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.legalPersonPhone')" prop="legalPersonPhone">
            <el-input v-model="form.legalPersonPhone" :placeholder="$t('Shop.inputLegalPersonPhoneTip')" clearable
              show-word-limit :maxlength="20" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.intro')" prop="intro">
            <el-input v-model="form.intro" :placeholder="$t('Shop.inputIntroTip')" clearable show-word-limit
              :maxlength="200" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.avatar')" prop="avatar">
            <upload-img v-model:image-url="form.avatar" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.picBackground')" prop="picBackground">

            <upload-img v-model:image-url="form.picBackground" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.area')" prop="province">
            <china-region-cascade v-model="regionValue" :props="{ checkStrictly: true, expandTrigger: 'hover' }"
              @change="changeRegion" placeholder="可输入省市区进行搜索" clearable filterable style="width: 100%" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.address')" prop="address">
            <el-input v-model="form.address" :placeholder="$t('Shop.inputAddressTip')" clearable show-word-limit
              :maxlength="255" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.mainProd')" prop="mainProd">
            <el-input v-model="form.mainProd" :placeholder="$t('Shop.inputMainProdTip')" clearable show-word-limit
              :maxlength="512" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.prodStyle')" prop="prodStyle">
            <el-input v-model="form.prodStyle" :placeholder="$t('Shop.inputProdStyleTip')" clearable show-word-limit
              :maxlength="512" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.marketPositioning')" prop="marketPositioning">
            <el-input v-model="form.marketPositioning" :placeholder="$t('Shop.inputMarketPositioningTip')" clearable
              show-word-limit :maxlength="512" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.factoryArea')" prop="factoryArea">
            <el-input v-model="form.factoryArea" :placeholder="$t('Shop.inputFactoryAreaTip')" clearable show-word-limit
              :maxlength="50" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.factoryYear')" prop="factoryYear">
            <el-input v-model="form.factoryYear" :placeholder="$t('Shop.inputFactoryYearTip')" clearable show-word-limit
              :maxlength="50" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.factoryRemark')" prop="factoryRemark">
            <el-input v-model="form.factoryRemark" :placeholder="$t('Shop.inputFactoryRemarkTip')" clearable
              show-word-limit :maxlength="512" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.picDoorstepPhoto')" prop="picDoorstepPhoto">

            <Upload v-model:imgList="form.picDoorstepPhoto" :limit="3" :multiple="true">
            </Upload>
            <!-- <upload-img v-model="form.picDoorstepPhoto"></upload-img> -->
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.picOfficeArea')" prop="picOfficeArea">

            <Upload :limit="18" v-model:imgList="form.picOfficeArea" :multiple="true">
            </Upload>

            <!-- <upload-img v-model="form.picOfficeArea"></upload-img> -->
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.picProductionArea')" prop="picProductionArea">

            <Upload :limit="18" v-model:imgList="form.picProductionArea"  :multiple="true">
            </Upload>

            <!-- <upload-img v-model="form.picProductionArea"></upload-img> -->
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.picWarehouseArea')" prop="picWarehouseArea">


            <Upload :limit="18" v-model:imgList="form.picWarehouseArea" :multiple="true">
            </Upload>

            <!-- <upload-img v-model="form.picWarehouseArea"></upload-img> -->
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.picFactoryShowroom')" prop="picFactoryShowroom">


            <Upload :limit="18" v-model:imgList="form.picFactoryShowroom" :multiple="true">
            </Upload>

            <!-- <upload-img v-model="form.picFactoryShowroom"></upload-img> -->
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item :label="$t('Shop.picOtherPhoto')" prop="picOtherPhoto">


            <Upload :limit="18" v-model:imgList="form.picOtherPhoto" :multiple="true">
            </Upload>
            <!-- <upload-img v-model="form.picOtherPhoto"></upload-img> -->
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">{{
          $t('common.confirmButtonText')
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="ShopDialog">
import { useDict } from '/@/hooks/dict';
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj } from '/@/api/bizs/Shop'
import Upload from "/@/components/biz/uploadImg.vue"
const emit = defineEmits(['refresh']);

// 定义i18n
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

const { proxy } = getCurrentInstance();
const ChinaRegionCascade = defineAsyncComponent(() => import('/@/components/biz/china-region-cascade.vue'));

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
// 定义字典
const { common_state_enable } = useDict('common_state_enable')


interface FormTypes {
  id: string;
  state: number;
  name: string;
  code: string;
  contacts: string;
  contactPhone: string;
  otherPhone: string;
  boss: string;
  bossPhone: string;
  legalPerson: string;
  legalPersonPhone: string;
  intro: string;
  avatar: string;
  picBackground: string;
  provinceCode: string;
  cityCode: string;
  areaCode: string;
  province: string;
  city: string;
  area: string;
  address: string;
  latitude: string;
  longitude: string;
  mainProd: string;
  prodStyle: string;
  marketPositioning: string;
  factoryArea: string;
  factoryYear: string;
  factoryRemark: string;
  picDoorstepPhoto: ImgItem[];
  picOfficeArea: ImgItem[];
  picProductionArea: ImgItem[];
  picWarehouseArea: ImgItem[];
  picFactoryShowroom: ImgItem[];
  picOtherPhoto: ImgItem[];
}

// 提交表单数据
const form = reactive<FormTypes>({
  id: '',
  state: 1,
  name: '',
  code: '',
  contacts: '',
  contactPhone: '',
  otherPhone: '',
  boss: '',
  bossPhone: '',
  legalPerson: '',
  legalPersonPhone: '',
  intro: '',
  avatar: '',
  picBackground: '',

  provinceCode: '',
  cityCode: '',
  areaCode: '',

  province: '',
  city: '',
  area: '',
  address: '',
  latitude: '',
  longitude: '',
  mainProd: '',
  prodStyle: '',
  marketPositioning: '',
  factoryArea: '',
  factoryYear: '',
  factoryRemark: '',
  picDoorstepPhoto: [],
  picOfficeArea: [],
  picProductionArea: [],
  picWarehouseArea: [],
  picFactoryShowroom: [],
  picOtherPhoto: [],
});
type ImgItem = { url: string }

type formKeys = keyof FormTypes
const getFileListFn = (file: ImgItem, str: formKeys) => {
  (form[str] as ImgItem[]).push(file)
}
//
const delImage = (image: string, str: formKeys) => {
  let index = (form[str] as ImgItem[]).findIndex((el: ImgItem) => el.url == image)
  if (index !== -1) {
    (form[str] as ImgItem[]).splice(index, 1)
  }
}

// 定义校验规则
import { rule } from '/@/utils/validate';
import {getFileUri} from "/@/utils/util";
const dataRules = ref({
  state: [{ required: true, message: t('Shop.inputStateTip'), trigger: 'blur' }],
  name: [{ required: true, message: t('Shop.inputNameTip'), trigger: 'blur' }],
  contacts: [{ required: false, message: t('Shop.inputContactsTip'), trigger: 'blur' }],
  contactPhone: [{ required: false, message: t('Shop.inputContactPhoneTip'), trigger: 'blur' }, {
    validator: rule.mobileAndFixPhone,
    trigger: 'blur'
  }],
  otherPhone: [{ required: false, message: t('Shop.inputOtherPhoneTip'), trigger: 'blur' }, {
    validator: rule.mobileAndFixPhone,
    trigger: 'blur'
  }],
  boss: [{ required: false, message: t('Shop.inputBossTip'), trigger: 'blur' }],
  bossPhone: [{ required: false, message: t('Shop.inputBossPhoneTip'), trigger: 'blur' }, {
    validator: rule.mobileAndFixPhone,
    trigger: 'blur'
  }],
  legalPerson: [{ required: false, message: t('Shop.inputLegalPersonTip'), trigger: 'blur' }],
  legalPersonPhone: [{
    required: false,
    message: t('Shop.inputLegalPersonPhoneTip'),
    trigger: 'blur'
  }, { validator: rule.mobileAndFixPhone, trigger: 'blur' }],
  intro: [{ required: false, message: t('Shop.inputIntroTip'), trigger: 'blur' }],
  avatar: [{ required: false, message: t('Shop.inputAvatarTip'), trigger: 'blur' }],
  picBackground: [{ required: false, message: t('Shop.inputPicBackgroundTip'), trigger: 'blur' }],
  province: [{ required: false, message: t('Shop.inputProvinceTip'), trigger: 'blur' }],
  city: [{ required: false, message: t('Shop.inputCityTip'), trigger: 'blur' }],
  area: [{ required: false, message: t('Shop.inputAreaTip'), trigger: 'blur' }],
  address: [{ required: false, message: t('Shop.inputAddressTip'), trigger: 'blur' }],
  mainProd: [{ required: false, message: t('Shop.inputMainProdTip'), trigger: 'blur' }],
  prodStyle: [{ required: false, message: t('Shop.inputProdStyleTip'), trigger: 'blur' }],
  marketPositioning: [{ required: false, message: t('Shop.inputParketPositioningTip'), trigger: 'blur' }],
  factoryArea: [{ required: false, message: t('Shop.inputFactoryAreaTip'), trigger: 'blur' }],
  factoryYear: [{ required: false, message: t('Shop.inputFactoryYearTip'), trigger: 'blur' }],
  factoryRemark: [{ required: false, message: t('Shop.inputFactoryRemarkTip'), trigger: 'blur' }],
  picDoorstepPhoto: [{ required: false, message: t('Shop.inputPicDoorstepPhotoTip'), trigger: 'blur' }],
  picOfficeArea: [{ required: false, message: t('Shop.inputPicOfficeAreaTip'), trigger: 'blur' }],
  picProductionArea: [{ required: false, message: t('Shop.inputPicProductionAreaTip'), trigger: 'blur' }],
  picWarehouseArea: [{ required: false, message: t('Shop.inputPicWarehouseAreaTip'), trigger: 'blur' }],
  picFactoryShowroom: [{ required: false, message: t('Shop.inputPicFactoryShowroomTip'), trigger: 'blur' }],
  picOtherPhoto: [{ required: false, message: t('Shop.inputPicOtherPhotoTip'), trigger: 'blur' }],
})

// 地区信息
const regionValue = ref()

// 图片回显数据
const picMap = reactive({
  avatar: '',
  picBackground: '',
  picDoorstepPhoto: [],
  picOfficeArea: [],
  picProductionArea: [],
  picWarehouseArea: [],
  picFactoryShowroom: [],
  picOtherPhoto: [],
})

// 打开弹窗
const openDialog = (id: string) => {
  visible.value = true
  form.id = ''

  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });

  // 获取shop信息
  if (id) {
    form.id = id
    initFormData(id)
  }
};

// [{url:""}] ==> [""]
const proceArr = (arr: { url: string }[]): string[] => {
  let newArr = arr.map((el: { url: string }) => el.url)
  return newArr
}

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {
  });
  if (!valid) return false;

  //
  let submitObj = {
    ...form,
    picOfficeArea: proceArr(form.picOfficeArea),
    picDoorstepPhoto: proceArr(form.picDoorstepPhoto),
    picProductionArea: proceArr(form.picProductionArea),
    picWarehouseArea: proceArr(form.picWarehouseArea),
    picFactoryShowroom: proceArr(form.picFactoryShowroom),
    picOtherPhoto: proceArr(form.picOtherPhoto),
  }

  try {
    loading.value = true;
    form.id ? await putObj(submitObj) : await addObj(submitObj);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};

// 初始化表单数据
const initFormData = (id: string) => {
  // 获取数据
  loading.value = true
  getObj(id).then((res: any) => {
    Object.assign(form, res.data, {
      picOfficeArea: imgUrlFn(res.data.picOfficeArea),
      picDoorstepPhoto: imgUrlFn(res.data.picDoorstepPhoto),
      picProductionArea: imgUrlFn(res.data.picProductionArea),
      picWarehouseArea: imgUrlFn(res.data.picWarehouseArea),
      picFactoryShowroom: imgUrlFn(res.data.picFactoryShowroom),
      picOtherPhoto: imgUrlFn(res.data.picOtherPhoto),
    })
    echoPic(res.data)
    echoRegion(res.data)
  }).finally(() => {
    loading.value = false
  })
};

const imgUrlFn = (imglist: string[]) => {
  return imglist.map((el: string) => {
    return {
      url: el
    }
  })
}



// 回显地区
const echoRegion = (data: { provinceCode: any; cityCode: any; areaCode: any; }) => {
  if (!data) {
    return
  }
  const array = []
  if (data.provinceCode) {
    array.push(data.provinceCode)
  }
  if (data.cityCode) {
    array.push(data.cityCode)
  }
  if (data.areaCode) {
    array.push(data.areaCode)
  }
  regionValue.value = array
}

// 回显图片
const echoPic = (data: any) => {
  picMap.avatar = getFileUri(data.avatar)
  picMap.picBackground = getFileUri(data.picBackground)
}

// change-图片
// const changePic = (e: { fileName: any; }, attr: string) => {
//   // console.log('changePic', e, attr)
//   form[attr] = e.fileName
//   picMap[attr] = e
// }

// 选择区域
const changeRegion = (val: string | any[], checkedNode: { pathLabels: any; data: { lng: string; lat: string; }; }) => {
  // console.log('changeRegion', val, checkedNode)

  if (val && val.length > 0) {
    // console.log('checkedNode', checkedNode)
    const pathLabels = checkedNode.pathLabels

    form.longitude = checkedNode.data.lng
    form.latitude = checkedNode.data.lat
    // console.log(`lng,lat: ${form.longitude},${form.latitude}`)

    if (val.length == 1) {
      form.provinceCode = val[0]
      form.province = pathLabels[0]
    }
    if (val.length == 2) {
      form.provinceCode = val[0]
      form.cityCode = val[1]

      form.province = pathLabels[0]
      form.city = pathLabels[1]
    }
    if (val.length == 3) {
      form.provinceCode = val[0]
      form.cityCode = val[1]
      form.areaCode = val[2]

      form.province = pathLabels[0]
      form.city = pathLabels[1]
      form.area = pathLabels[2]
    }
  } else {
    form.provinceCode = ''
    form.cityCode = ''
    form.areaCode = ''

    form.province = ''
    form.city = ''
    form.area = ''

    regionValue.value = []
  }
}

// 暴露变量
defineExpose({
  openDialog
});
</script>
